package com.example.j11.demo;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhoudong
 * @version 0.1
 * @date 2018/12/14 11:58
 */
public class FullDemo {

    public static void main(String[] args) throws Exception {
        /*oldJava();
        System.out.println("--------");
        newJava();*/
    }

    /**
     * 下面两个方法，比较JAVA8以前及JAVA8以后，完成同一块业务所需的代码量
     *
     * 需求：
     *  对http://httpbin.org/get 调用5次，分别传值1,2,3,4,5，并分析返回值，args.param < 3 输出
     */

    /*public static void oldJava() throws Exception {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        for(int i : list){
            String result = httpGet("http://httpbin.org/get?params=" + i);
            if(StringUtils.isNoneBlank(result)){
                int resp = JSONObject.parseObject(result).getJSONObject("args").getInteger("params");
                if(resp < 3) System.out.println(resp);  // 输出：1，2
            }
        }
    }
    // Java11 之前的get请求
    private static String httpGet(String url) throws Exception {
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();
        BufferedReader dataIn = new BufferedReader(
                new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = dataIn.readLine()) != null) sb.append(line);
        return sb.toString();
    }

    // java 11
    public static void newJava(){
        var list = List.of(1,2,3,4,5);
        list.parallelStream()                   // 并行访问，多线程。
                .map(FullDemo::java11HttpGet)
                .filter(i -> i < 3)
                .forEach(System.out::println);  // 输出：1，2
    }
    // 发起get请求，并返回返回值
    private static int java11HttpGet(Integer i) {
        var request = HttpRequest.newBuilder()
                .uri(URI.create("http://httpbin.org/get?params=" + i))
                .build();
        try {
            var result = HttpClient.newBuilder()
                    .build()
                    .send(request, HttpResponse.BodyHandlers.ofString());
            if(StringUtils.isNotBlank(result.body()))
                return JSONObject.parseObject(result.body()).getJSONObject("args").getInteger("params");
        } catch (Exception e) {e.printStackTrace();}
        return 0;
    }*/
}
